package com.sjtu.rental.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.sjtu.rental.common.Constant;
import com.sjtu.rental.common.PaginationSupport;
import com.sjtu.rental.entity.House;
import com.sjtu.rental.entity.ShowingRecord;
import com.sjtu.rental.entity.SysVariable;
import com.sjtu.rental.entity.UserInfo;
import com.sjtu.rental.form.HouseForm;
import com.sjtu.rental.form.SearchForm;
import com.sjtu.rental.services.HouseService;
import com.sjtu.rental.services.UserService;
import com.sjtu.rental.services.VariableService;

/**
 * 登记房源
 * 
 * @author Jessdy
 * 
 */
@Controller
@RequestMapping("/house")
public class HouseController {

	@Autowired
	private VariableService variableService;

	@Autowired
	private HouseService houseService;

	@Autowired
	private UserService userService;

	/**
	 * 登记房源
	 * 
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String init(Model model) {
		List<SysVariable> districts = variableService
				.getVarsList(VariableService.DISTRICT);
		model.addAttribute("districts", districts);
		model.addAttribute("house", new HouseForm());
		model.addAttribute("searchForm", new SearchForm());
		return "house";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String saveHouse(
			@Valid @ModelAttribute("house") HouseForm houseForm, Model model,
			HttpSession session) {
		UserInfo user = (UserInfo) session.getAttribute("user");
		House house = houseForm.getHouse();
		house.setApproveState(Constant.HOUSE_STATE_UNCONFIRM);
		house.setHouseType(house.getRoom() + "-" + house.getHall() + "-"
				+ house.getBathroom() + "-" + house.getFloor() + "-"
				+ house.getAllFloor());

		house.setCreator(user.getUiId());
		house.setCreateDate(new Date());
		house.setIsDeleted(Constant.IS_NOT_DELETED);
		houseService.saveOrUpdate(house, houseForm.getFiles());
		model.addAttribute("searchForm", new SearchForm());
		return "houseSuccess";
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String editHouse(@PathVariable Long id, Model model,
			HttpSession session) {
		UserInfo user = (UserInfo) session.getAttribute("user");
		House house = houseService.getById(id);
		if (user.getUiId().equals(house.getCreator())) {
			HouseForm form = new HouseForm();
			form.setHouse(house);
			List<SysVariable> districts = variableService
					.getVarsList(VariableService.DISTRICT);
			model.addAttribute("districts", districts);
			model.addAttribute("house", form);
		}
		model.addAttribute("searchForm", new SearchForm());
		return "house";
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public String deleteHouse(@PathVariable Long id, Model model,
			HttpSession session) {
		UserInfo user = (UserInfo) session.getAttribute("user");
		House house = houseService.getById(id);
		if (user.getUiId().equals(house.getCreator()) || user.getUiUsernameType() == 9) {
			house.setIsDeleted(1);
			houseService.saveOrUpdate(house, null);
		}
		model.addAttribute("searchForm", new SearchForm());
		return user.getUiUsernameType() == 9 ? "redirect:/user/houseall" : "redirect:/user/house";
	}

	@RequestMapping(value = "/show/{id}", method = RequestMethod.GET)
	public String showHouse(@PathVariable Long id, Model model) {
		House house = houseService.getById(id);
		model.addAttribute("house", house);
		Long userId = house.getCreator();
		UserInfo userInfo = userService.getUserById(userId);
		model.addAttribute("u", userInfo);
		model.addAttribute("searchForm", new SearchForm());
		return "houseShow";
	}

	@RequestMapping(value = "/reserve/{id}", method = RequestMethod.POST)
	public String reserve(@PathVariable Long id, HttpServletRequest request,
			HttpSession session, HttpServletResponse response)
			throws IOException {
		UserInfo user = (UserInfo) session.getAttribute("user");
		String showingDate = request.getParameter("showingDate");
		String contactTime = URLDecoder.decode(request
				.getParameter("contactTime"), "UTF-8");
		String remark = URLDecoder.decode(request.getParameter("remark"),
				"UTF-8");
		try {
			boolean result = houseService.reserve(id, user.getUiId(),
					showingDate, contactTime, remark);
			if (result) {
				response.getWriter().write("success");
			} else {
				response.getWriter().write("failed");
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.getWriter().write("failed");
		} finally {
			response.getWriter().flush();
			response.getWriter().close();
		}
		return "";
	}

	@RequestMapping(value = "/appointment/{id}", method = RequestMethod.POST)
	public String appointment(
			@PathVariable Long id,
			@RequestParam(value = "page", required = false, defaultValue = "0") String page,
			Model model) {
		PaginationSupport p = houseService.getAppointments(id, Integer
				.parseInt(page));
		p.setUrl("/house/appointment/" + id + "&page=");
		model.addAttribute("p", p);
		return "user/houseAppointments";
	}

	@RequestMapping(value = "/appointment/{id}/agree", method = RequestMethod.GET)
	public String agreeAppointment(@PathVariable Long id, Model model) {
		houseService
				.changeAppointmentState(id, ShowingRecord.AGREE_APPOINTMENT);
		return "redirect:/user/house";
	}

	@RequestMapping(value = "/appointment/{id}/deny", method = RequestMethod.GET)
	public String denyAppointment(@PathVariable Long id, Model model) {
		houseService.changeAppointmentState(id, ShowingRecord.DENY_APPOINTMENT);
		return "redirect:/user/house";
	}

	@RequestMapping(value = "/appointment/{id}/finish", method = RequestMethod.GET)
	public String finishAppointment(@PathVariable Long id, Model model) {
		houseService.changeAppointmentState(id,
				ShowingRecord.FINISH_APPOINTMENT);
		return "redirect:/user/house";
	}

	@RequestMapping(value = "/appointment/{id}/rent", method = RequestMethod.GET)
	public String rentHouse(@PathVariable Long id, Model model) {
		houseService.rentHouse(id);
		return "redirect:/user/house";
	}

	@RequestMapping(value = "/order/{id}", method = RequestMethod.POST)
	public String order(
			@PathVariable Long id,
			@RequestParam(value = "page", required = false, defaultValue = "0") String page,
			Model model) {
		PaginationSupport p = houseService
				.getOrders(id, Integer.parseInt(page));
		p.setUrl("/house/order/" + id + "&page=");
		model.addAttribute("p", p);
		return "user/houseOrders";
	}

	@RequestMapping(value = "/checkout/{id}", method = RequestMethod.GET)
	public String checkoutHouse(@PathVariable Long id, Model model) {
		houseService.checkoutHouse(id);
		return "redirect:/user/house";
	}
	
	@RequestMapping(value = "/{id}/pass", method = RequestMethod.GET)
	public String approvePass(@PathVariable Long id, Model model,
			HttpSession session) {
		UserInfo user = (UserInfo) session.getAttribute("user");
		if (user.getUiUsernameType() == 9) {
			houseService.changeHouseState(id, Constant.HOUSE_STATE_CONFIRMED);
		}
		return "redirect:/user/houseall";
	}
}
